# import datetime
import json
import time
import jwt
import requests
from django.contrib.auth.decorators import login_required
from django.contrib.auth.hashers import make_password, check_password
from django.core import serializers
from django.http import JsonResponse, HttpResponse
from django.shortcuts import render, redirect
from .models import (User, UserExtend, Article, Reply, video)
from .utils.commonConfig import (returnOriginJson, articleClass, tokenTag)
from django.db.models import Q, Max
from .outerMethods.zhihu.getZhihuData import getZhihuHots
from .outerMethods.bilibili.getBiliData import getBiliVideoHotList
from .outerMethods.douban.getDouban import getDoubanData
from .outerMethods.weixin.weixinPackage import getWeixinData
from django.contrib import auth
from rest_framework.authtoken.models import Token
from rest_framework.permissions import IsAuthenticated, AllowAny
from rest_framework.authentication import TokenAuthentication
from .utils.TokenAuthenticationUtils.AutoExpireTokenUtils import ExpiringTokenAuthentication
from django.views import View
from django.http import HttpResponse
from rest_framework.views import APIView
from .utils.TokenAuthenticationUtils.AuthenByDecorator import loginRequeired
from rentalsite.settings import tokenExpireDays
# from datetime import datetime # 原来用的注释掉
from django.utils import timezone as datetime  # 不想大面积修改就这么做
from .utils.RedisUtils.redisForApi import RedisUtilClass
# Create your views here.

# ----------------------------------------------------
# Django project parameters need to be initialized.
# ----------------------------------------------------
redisObj = RedisUtilClass()


# ----------------------------------------------------
# 注册、登录、 登出   User.objects.create
# ----------------------------------------------------
def register(request):
    """
    Getting username and password from register page, then do something about register checking.
    :param request:
    :return:
    """
    if request.method == 'GET':
        return JsonResponse(returnOriginJson)
    elif request.method == 'POST':
        telephone = '13147164206'
        #  1,teltephone cans be changed to any patameters.
        username = json.loads(request.body).get('username')
        password = json.loads(request.body).get('pass')
        repeatPassword = json.loads(request.body).get('checkPass')
        if User.objects.filter(username=username).exists():
            returnOriginJson['existed'] = 'Y'
            return JsonResponse(returnOriginJson)
        else:
            if password == repeatPassword:
                # create_user can change the pwd to be encrypted.
                # OnetooneFiled can inline 2 tables.
                userObj = User.objects.create_user(username=username, password=password)
                newUser = UserExtend(user=userObj, telephone=telephone)
                newUser.save()
                returnOriginJson['registered'] = 'Y'
                return JsonResponse(returnOriginJson)
            else:
                returnOriginJson['registered'] = 'N'
                returnOriginJson['info'] = 'Please enter the same password.'
                return JsonResponse(returnOriginJson)


def login(request):
    """
    Login to the index page.
    :param request:
    :return:
    """
    if request.method == "GET":
        return JsonResponse(returnOriginJson)
    elif request.method == "POST":
        '''登录获取token方法'''
        username = json.loads(request.body).get('username')
        pwd = json.loads(request.body).get('password')
        results = dict(returnOriginJson)
        isExsited = User.objects.filter(username=username).exists()
        if isExsited:
            userObj = auth.authenticate(username=username, password=pwd)
            if userObj:
                results['isLogin'] = bool(True)
                params = {
                    'username': username,
                    'password': pwd,
                    'tokentime': time.mktime(datetime.datetime.now().timetuple())
                }
                encoded_jwt = jwt.encode(params, 'secretKey', algorithm='HS256')
                user = User.objects.get(username=username)
                userExt = UserExtend.objects.get(user=user)
                strToken = encoded_jwt.decode()

                userExt.token = strToken
                print("encoded_jwt", type(encoded_jwt), strToken)
                userExt.tokenExpireTime = datetime.datetime.now() + datetime.timedelta(days=tokenExpireDays)
                userExt.save()
                results['username'] = userObj.username
                results['userid'] = userExt.user_id
                results['token'] = strToken

                results['tokenExpireTime'] = userExt.tokenExpireTime
                return JsonResponse(results)
            else:
                results['isLogin'] = 'Password is wrong.'
                return JsonResponse(results)
        else:
            results['isLogin'] = 'There is no such user.'
            return JsonResponse(results)


@loginRequeired
def logout(request):
    """
        Login out the index page.
        :param request:
        :return:
        """
    if request.method == 'GET':
        return JsonResponse(returnOriginJson)
    elif request.method == 'POST':
        results = dict(returnOriginJson)
        # username = json.loads(request.body).get('username')
        username = request.username

        if tokenTag in list(request.META.keys()):
            tokenAuth = bytes(str(request.META[tokenTag]), encoding='utf8')
            try:
                decodedTokenAuth = jwt.decode(tokenAuth, 'secretKey', algorithm='HS256')
                decodedUser = dict(decodedTokenAuth).get('username', None)
                if username == decodedUser:
                    userid = User.objects.filter(username=username).values('id')[0].get('id', 0)
                    clearTokenObj = UserExtend.objects.get(user=userid)
                    clearTokenObj.token = ''
                    clearTokenObj.tokenExpireTime = datetime.datetime.now()
                    clearTokenObj.save()
                    results['info'] = 'Logout sueecss.'
                    return JsonResponse(results)
                else:
                    results['info'] = 'Information error.'
                    return JsonResponse(results)
            except Exception as e:
                print(e)
        else:
            results['info'] = 'No token in headers'
            return JsonResponse(results)


@loginRequeired
def tokenTest(request):
    if request.method == 'GET':
        return JsonResponse(returnOriginJson)
    elif request.method == 'POST':
        results = dict(returnOriginJson)
        username = json.loads(request.body).get('username')
        print('sssss', request.username)
        tokenAuth = bytes(str(request.META['HTTP_AUTHORIZATION_TOKEN']), encoding='utf8')
        token = json.loads(request.body).get('token')
        results['token'] = token
        results['username'] = request.username
        return JsonResponse(results, safe=False)


def testAPI(request):
    if request.method == 'GET':
        return JsonResponse(returnOriginJson)
    elif request.method == 'POST':
        results = dict(returnOriginJson)
        telephone = json.loads(request.body).get('telephone')
        telephoneObj = UserExtend.objects.get(telephone=telephone)
        telephoneObj.signature = str(telephoneObj.signature) + 'crontab ok'
        telephoneObj.save()
        results['info'] = str(telephone) + str(" run crontab OK!")
        return JsonResponse(results, safe=False)


@loginRequeired
def getUserInfo(request):
    """
    Getting user information by username(unique).
    :param request:
    :return:
    """
    if request.method == 'GET':
        return JsonResponse(returnOriginJson)
    elif request.method == 'POST':
        username = request.username if request.username else json.loads(request.body).get('username')
        userObj = User.objects.filter(username=username).values('id', 'is_superuser', 'is_staff', 'is_active',
                                                                'username', 'first_name', 'last_name', 'email')
        ueserExtendObj = UserExtend.objects.filter(user_id=list(userObj)[0].get('id'))\
            .values('user_id', 'telephone', 'isDelete', 'isValid', 'roleType', 'userLevel', 'score', 'signature')
        results = dict(returnOriginJson)
        results['user'] = list(userObj)
        results['userExtend'] = list(ueserExtendObj)
        redisKeyForgetUserInfo = 'getUserInfo_' + str(username)
        if redisObj.get(redisKeyForgetUserInfo) is not None:
            print('has redis')
            resultsByRedis = redisObj.get(redisKeyForgetUserInfo)
            print('type,', type(resultsByRedis))
            return JsonResponse(json.loads(resultsByRedis.decode()), safe=False)
        else:
            redisObj.setRedis(redisKeyForgetUserInfo , json.dumps(results))
            print('has not redis')
            return JsonResponse(results, safe=False)


# ----------------------------------------------------
# 文章,添加文章
# ----------------------------------------------------
def addArticle(request):
    '''
    Adding article.
    :param request:
    :return:
    '''
    if request.method == "GET":
        return JsonResponse(returnOriginJson)
    elif request.method == "POST":
        formData = json.loads(request.body)
        # title = formData.get('title')
        # subtitle = json.loads(request.body).get('subtitle')
        classfy = json.loads(request.body).get('classfy')
        # onshelf = json.loads(request.body).get('onshelf')
        keyword = json.loads(request.body).get('keyword')
        content = json.loads(request.body).get('content')
        # introduction = json.loads(request.body).get('introduction')
        articleClassfy = articleClass.get(classfy)
        print('addArticle:', content)
        print(str(content).replace(' ','&nbsp'))
        formatedContent = str(content).replace(' ','&nbsp&nbsp&nbsp&nbsp')


        articleObj = Article.objects.create(title=formData.get('title'), subtitle=formData.get('subtitle'),
                                            introduction=formData.get('introduction'), classfy=articleClassfy,
                                            onshelf=formData.get('onshelf'), keyword=formData.get('keyword'),
                                            content=formatedContent)
        articleObj.save()
        results = dict(returnOriginJson)
        results['info'] = 'created'
        return JsonResponse(results, safe=True)


def deleteArticle(request):
    '''
    Delete article.
    If the author match the userid, you can delete the article.
    :param request:
    :return:
    '''
    if request.method == "GET":
        return JsonResponse(returnOriginJson)
    elif request.method == "POST":
        try:
            articleID = json.loads(request.body).get('articleID')
            userid = json.loads(request.body).get('userid')
            articleObj = Article.objects.get(Q(id=articleID))
            results = dict(returnOriginJson)
            print("cunz?", bool(articleObj), articleObj.author.id, userid)
            if bool(articleObj):
                print("是否相等?", articleObj.author.id == int(userid))
                if articleObj.author.id == int(userid):
                    articleObj.isdeleted = 1
                    articleObj.save()
                    results['info'] = 'deleted'
                else:
                    results['info'] = 'No access to delte.'
            else:
                results['info'] = 'Not Existed this article.'
            return JsonResponse(results, safe=True)
        except Exception as error:
            print(error)


# @loginRequeired
def getArticle(request):
    '''
    Get article.
    :param request:
    :return:
    '''
    if request.method == "GET":
        return JsonResponse(returnOriginJson)
    elif request.method == "POST":

        articleCount = int(json.loads(request.body).get('articleCount'))
        articleObj = Article.objects.filter(Q(isdeleted=0) & Q(onshelf=1)).values('id', 'title', 'subtitle', 'introduction',
                                                    'content', 'link', 'keyword', 'classfy', 'hits', 'viewnum', 'ontop',
                                                    'iselite', 'author', 'create_time', 'update_time').order_by('-update_time')[:articleCount]
        print(list(articleObj))
        results = dict(returnOriginJson)
        results['info'] = list(articleObj)
        return JsonResponse(results, safe=True)


def getArticleByArticleID(request):
    '''
    Get article by article id.
    :param request:
    :return:
    '''
    if request.method == "GET":
        return JsonResponse(returnOriginJson)
    elif request.method == "POST":
        articleId = int(json.loads(request.body).get('articleId'))
        articleObj = Article.objects.filter(Q(isdeleted=0) & Q(onshelf=1) & Q(id=articleId)).values('id', 'title', 'subtitle', 'introduction',
                                                    'content', 'link', 'keyword', 'classfy', 'hits', 'viewnum', 'ontop',
                                                    'iselite', 'author', 'create_time', 'update_time').order_by('-update_time')
        addViewNumObj = Article.objects.get(id=articleId)
        addViewNumObj.viewnum = addViewNumObj.viewnum + 1
        addViewNumObj.save()
        print(list(articleObj))
        results = dict(returnOriginJson)
        results['info'] = list(articleObj)
        return JsonResponse(results, safe=True)


def getArticleByUserid(request):
    '''
    Get article by user.
    :param request:
    :return:
    '''
    if request.method == 'GET':
        return JsonResponse(returnOriginJson)
    elif request.method == 'POST':
        try:
            userid = json.loads(request.body).get('userid')
            startpage = json.loads(request.body).get('startpage')
            articlesByUser = Article.objects.filter(Q(isdeleted=0) & Q(onshelf=1) & Q(author=userid)).values('id',
                                                                                                             'title',
                                                                                                             'subtitle',
                                                                                                             'introduction',
                                                                                                             'content',
                                                                                                             'link',
                                                                                                             'keyword',
                                                                                                             'classfy',
                                                                                                             'hits',
                                                                                                             'viewnum',
                                                                                                             'ontop',
                                                                                                             'iselite',
                                                                                                             'author',
                                                                                                             'create_time',
                                                                                                             'update_time').order_by(
                '-update_time')
            results = dict(returnOriginJson)
            results['info'] = list(articlesByUser)
            return JsonResponse(results)
        except Exception as e:
            print(e)


# ============================================
# 文章评论
# ============================================
def addReplybyArticleID(request):
    """
    Add article comment by article id.
    :param request:
    :return:
    """
    if request.method == "GET":
        return JsonResponse(returnOriginJson)
    elif request.method == "POST":
        results = dict(returnOriginJson)
        formData = json.loads(request.body)
        lenArticleId = len(str(formData.get('article_id')))
        lenComment = len(str(formData.get('comment')))
        print('lenComment', lenComment)
        if lenArticleId > 0:
            try:
                if lenComment > 0:
                    articleObj = Article.objects.get(id=formData.get('article_id')).author
                    print("articleObj:", articleObj.id, articleObj.username)
                    articleCommentName = User.objects.filter(id=formData.get('article_comment_id')).values('username')
                    replyObj = Reply.objects.create(
                        # article_id must be Article object because of the structure of foreignkey model.
                        article_id=Article.objects.filter(id=formData.get('article_id')).first(),
                        article_author_id=User.objects.filter(id=articleObj.id).first(),
                        article_author_username=articleObj.username,
                        article_comment_id=formData.get('article_comment_id'),
                        article_comment_username=articleCommentName,
                        comment=formData.get('comment'))
                    """
                         "article_id": 16,			文章id
                            "article_author_id": "22",		文章作者id
                            "article_author_username": "zy",	文章作者名
                         "article_comment_id": "6",		评论者id
                            "article_comment_username": "zy5", 	评论者名称
                         "comment": "zy5给zy的文章16做了个，我觉得你的文章写得也还不错2。" 
                    """
                    replyObj.save()
                    results['info'] = 'commented success.'
                    return JsonResponse(results)
                else:
                    results['info'] = 'Conment should not be null.'
                    return JsonResponse(results)
            except Exception as e:
                print(e)
        else:
            results['info'] = 'Can not get article id.'
            return JsonResponse(results)


def showReply(request):
    """
    show reply by article id.
    :param request:
    :return:
    """
    if request.method == 'GET':
        return JsonResponse(returnOriginJson)
    elif request.method == "POST":
        try:
            formData = json.loads(request.body)
            articleid = formData.get('articleId')
            print("showReply", articleid)
            replyObj = Reply.objects.filter(Q(article_id=articleid) & Q(isdeleted=False)).values('article_id',
                                                                         'article_author_id',
                                                                         'article_author_username',
                                                                         'article_comment_id',
                                                                         'article_comment_username',
                                                                         'comment',
                                                                         'canbereply',
                                                                         'issoncomment',
                                                                         'isdeleted',
                                                                         'create_time',
                                                                         'update_time'
                                                               ).order_by('-update_time')
            print(replyObj)
            results = dict(returnOriginJson)
            results['info'] = list(replyObj)
            return JsonResponse(results)
        except Exception as e:
            print(e)


# ============================================
# 获取知乎热榜数据
# ============================================
def addToDatabasefromList(request):
    """
    Add list to database.
    :param request:
    :return:
    """
    if request.method == "GET":
        return JsonResponse(returnOriginJson)
    elif request.method == "POST":
        try:
            zhihudata = getZhihuHots()
            startTime = time.time()
            batchNo = time.strftime("%Y%m%d%H%M", time.localtime(time.time()))
            for index, data in enumerate(zhihudata):
                articleObj = Article.objects.create(title=data[2],
                                                    subtitle='subtitle',
                                                    introduction='introduction',
                                                    link=data[3],
                                                    hits=data[1],
                                                    classfy='zhihuhot' if index < 50 else 'zhihurecent',
                                                    onshelf=True,
                                                    keyword='知乎热榜' if index < 50 else '知乎近期100条',
                                                    content='知乎内容',
                                                    batchNo=int(batchNo),
                                                    )
                articleObj.save()
            endTime = time.time()
            results = dict(returnOriginJson)
            results['classfy'] = '知乎热榜'
            results['info'] = 'Successfully inserted {} articles in {} seconds.'.format(len(zhihudata), endTime-startTime)
            return JsonResponse(results)
        except Exception as e:
            print(e)

@loginRequeired
def getZhihuArticle(request):
    if request.method == "GET":
        return JsonResponse(returnOriginJson)
    elif request.method == "POST":
        try:
            classfy = str(json.loads(request.body).get('classfy'))
            maxBatchNo = Article.objects.filter(classfy=classfy).aggregate(Max('batchNo'))['batchNo__max']
            articleObj = Article.objects.filter(
                Q(isdeleted=0) & Q(onshelf=1) & Q(classfy=classfy) & Q(batchNo=maxBatchNo)).values('id', 'title', 'subtitle',
                                                                                          'introduction',
                                                                                          'content', 'link', 'keyword',
                                                                                          'classfy', 'hits', 'viewnum',
                                                                                          'ontop',
                                                                                          'iselite', 'author',
                                                                                          'create_time',
                                                                                          'update_time').order_by(
                '-hits')
            print(list(articleObj))
            results = dict(returnOriginJson)
            results['info'] = list(articleObj)
            return JsonResponse(results, safe=True)
        except Exception as e:
            print(e)


# ============================================
# B站热榜数据
# ============================================
def addBiliHotVideo(request):
    if request.method == "GET":
        return JsonResponse(returnOriginJson)
    elif request.method == "POST":
        try:
            biliData = getBiliVideoHotList()
            print("biliData", biliData)
            startTime = time.time()
            for data in biliData:
                print(data)
                try:
                    videoObj = video.objects.create(
                        author=data[0],
                        avatorLink=data[1],
                        title=str(data[2]),
                        videoLink=data[3],
                        videoPic=data[4],
                        videoTimeLong=data[5],
                        classfy=data[6],
                        pubDate=data[7],
                        pubLocation=data[8],
                        hitRank=data[9],
                        view=data[10],
                        favorite=data[11],
                        onshelf=True,
                        batchNo=int(time.strftime("%Y%m%d%H%M", time.localtime(time.time()))),
                    )
                    videoObj.save()
                except Exception as e:
                    print(e)
                    continue
            endTime = time.time()
            results = dict(returnOriginJson)
            results['classfy'] = 'bili'
            results['info'] = 'Successfully inserted {} videoes in {} seconds.'.format(len(biliData), endTime-startTime)
            return JsonResponse(results, safe=True)
        except Exception as e:
            print(e)


def getBiliHotVideo(request):
    if request.method == "GET":
        return JsonResponse(returnOriginJson)
    elif request.method == "POST":
        try:
            maxBatchNo = video.objects.all().aggregate(Max('batchNo'))['batchNo__max']
            videoObj = video.objects.filter(
                Q(isdeleted=0) & Q(onshelf=1) & Q(batchNo=maxBatchNo)).values('author', 'avatorLink', 'title',
                                                       'videoLink',
                                                       'videoPic', 'videoTimeLong', 'classfy',
                                                       'pubDate', 'pubLocation', 'hitRank',
                                                       'view',
                                                       'favorite', 'ontop', 'iselite',
                                                       'create_time',
                                                       'update_time').order_by(
                '-view')
            print(list(videoObj))
            results = dict(returnOriginJson)
            results['length'] = len(list(videoObj))
            results['info'] = list(videoObj)
            return JsonResponse(results, safe=True)
        except Exception as e:
            print(e)


def addBaiduHot(request):
    if request.method == 'GET':
        return JsonResponse(returnOriginJson)
    elif request.method == 'POST':
        results = dict(returnOriginJson)
        try:
            baiduHotUrl = 'https://tenapi.cn/baiduhot/'
            req = requests.get(url=baiduHotUrl, timeout=5)
            baiduHotData = req.json().get('list')
            startTime = time.time()
            for index, data in enumerate(baiduHotData):
                name = data.get('name', None)
                print(name)
                batchNo = time.strftime("%Y%m%d%H%M", time.localtime(time.time()))
                articleObj = Article.objects.create(title=data.get('name', None),
                                                    subtitle='baidu subtitle',
                                                    introduction='baidu introduction',
                                                    link=data.get('url', None),
                                                    hits=data.get('hot', None),
                                                    classfy='baiduhot',
                                                    onshelf=True,
                                                    keyword='百度热榜',
                                                    content='百度内容',
                                                    batchNo=int(batchNo),
                                                    )
                articleObj.save()
            endTime = time.time()
            results = dict(returnOriginJson)
            results['classfy'] = '百度热榜'
            results['info'] = 'Successfully inserted baidu in {} seconds.'.format(endTime - startTime)
            return JsonResponse(results)
        except Exception as e:
            pass


def getBaiduHot(request):
    if request.method == "GET":
        return JsonResponse(returnOriginJson)
    elif request.method == "POST":
        results = dict(returnOriginJson)
        try:
            classfy = str(json.loads(request.body).get('classfy'))
            maxBatchNo = Article.objects.filter(classfy=classfy).aggregate(Max('batchNo'))['batchNo__max']
            articleObj = Article.objects.filter(
                Q(isdeleted=0) & Q(onshelf=1) & Q(classfy=classfy) & Q(batchNo=maxBatchNo)).values('id', 'title',
                                                                                                   'subtitle',
                                                                                                   'introduction',
                                                                                                   'content', 'link',
                                                                                                   'keyword',
                                                                                                   'classfy', 'hits',
                                                                                                   'viewnum',
                                                                                                   'ontop',
                                                                                                   'iselite', 'author',
                                                                                                   'create_time',
                                                                                                   'update_time').order_by(
                '-hits')
            print(list(articleObj))
            results = dict(returnOriginJson)
            results['info'] = list(articleObj)
            return JsonResponse(results, safe=True)
        except Exception as e:
            print(e)


def addWeiboHot(request):
    if request.method == "GET":
        return JsonResponse(returnOriginJson, safe=True)
    elif request.method == "POST":
        try:
            weiboHotUrl = 'https://tenapi.cn/resou/'
            req = requests.get(url=weiboHotUrl, timeout=5)
            baiduHotData = req.json().get('list')
            startTime = time.time()
            for index, data in enumerate(baiduHotData):
                print(data)
                name = data.get('name', None)
                print(name)
                batchNo = time.strftime("%Y%m%d%H%M", time.localtime(time.time()))
                articleObj = Article.objects.create(title=data.get('name', None),
                                                    subtitle='weibo subtitle',
                                                    introduction='weibo introduction',
                                                    link=data.get('url', None),
                                                    hits=data.get('hot', None),
                                                    classfy='weibohot',
                                                    onshelf=True,
                                                    keyword='微博热榜',
                                                    content='微博内容',
                                                    batchNo=int(batchNo),
                                                    )
                articleObj.save()
            endTime = time.time()
            results = dict(returnOriginJson)
            results['classfy'] = '微博热榜'
            results['info'] = 'Successfully inserted weibo data in {} seconds.'.format(endTime - startTime)
            return JsonResponse(results)
        except Exception as e:
            raise Exception


def getWeiboHot(request):
    if request.method == "GET":
        return JsonResponse(returnOriginJson)
    elif request.method == "POST":
        results = dict(returnOriginJson)
        try:
            classfy = str(json.loads(request.body).get('classfy'))
            maxBatchNo = Article.objects.filter(classfy=classfy).aggregate(Max('batchNo'))['batchNo__max']
            articleObj = Article.objects.filter(
                Q(isdeleted=0) & Q(onshelf=1) & Q(classfy=classfy) & Q(batchNo=maxBatchNo)).values('id', 'title',
                                                                                                   'subtitle',
                                                                                                   'introduction',
                                                                                                   'content', 'link',
                                                                                                   'keyword',
                                                                                                   'classfy', 'hits',
                                                                                                   'viewnum',
                                                                                                   'ontop',
                                                                                                   'iselite', 'author',
                                                                                                   'create_time',
                                                                                                   'update_time').order_by(
                '-hits')
            print(list(articleObj))
            results = dict(returnOriginJson)
            results['info'] = list(articleObj)
            return JsonResponse(results, safe=True)
        except Exception as e:
            print(e)


def addDouyinHot(request):
    if request.method == "GET":
        return JsonResponse(returnOriginJson)
    elif request.method == "POST":
        results = dict(returnOriginJson)
        try:
            douyinHotUrl = 'https://tenapi.cn/douyinresou/'
            douyinSearchUrl = 'https://www.douyin.com/search/'
            req = requests.get(url=douyinHotUrl, timeout=5)
            baiduHotData = req.json().get('list')
            print(baiduHotData)
            startTime = time.time()
            for index, data in enumerate(baiduHotData):
                name = data.get('name', None)
                batchNo = time.strftime("%Y%m%d%H%M", time.localtime(time.time()))
                articleObj = Article.objects.create(title=data.get('name', None),
                                                    subtitle='douyin subtitle',
                                                    introduction='douyin introduction',
                                                    link=douyinSearchUrl + data.get('name', None),
                                                    hits=data.get('hot', None),
                                                    classfy='douyinhot',
                                                    onshelf=True,
                                                    keyword='抖音热榜',
                                                    content='抖音内容',
                                                    batchNo=int(batchNo),
                                                    )
                articleObj.save()
            endTime = time.time()
            results = dict(returnOriginJson)
            results['classfy'] = '抖音热榜'
            results['info'] = 'Successfully inserted douyin data in {} seconds.'.format(endTime - startTime)
            return JsonResponse(results)
        except Exception as e:
            raise Exception


def getDouyinHot(request):
    if request.method == "GET":
        return JsonResponse(returnOriginJson)
    elif request.method == "POST":
        results = dict(returnOriginJson)
        try:
            classfy = str(json.loads(request.body).get('classfy'))
            # classfy = 'douyinhot'
            maxBatchNo = Article.objects.filter(classfy=classfy).aggregate(Max('batchNo'))['batchNo__max']
            articleObj = Article.objects.filter(
                Q(isdeleted=0) & Q(onshelf=1) & Q(classfy=classfy) & Q(batchNo=maxBatchNo)).values('id', 'title',
                                                                                                   'subtitle',
                                                                                                   'introduction',
                                                                                                   'content', 'link',
                                                                                                   'keyword',
                                                                                                   'classfy', 'hits',
                                                                                                   'viewnum',
                                                                                                   'ontop',
                                                                                                   'iselite', 'author',
                                                                                                   'create_time',
                                                                                                   'update_time').order_by(
                '-hits')
            results = dict(returnOriginJson)
            results['info'] = list(articleObj)
            print(results)
            return JsonResponse(results, safe=True)
        except Exception as e:
            print(e)


def addDoubanData(request):
    if request.method == "GET":
        return JsonResponse(returnOriginJson)
    elif request.method == "POST":
        results = dict(returnOriginJson)
        try:
            doubanList = getDoubanData()
            print(doubanList)
            startTime = time.time()
            for index, data in enumerate(doubanList):
                batchNo = time.strftime("%Y%m%d%H%M", time.localtime(time.time()))
                articleObj = Article.objects.create(title=data[0],
                                                    subtitle=data[2],
                                                    introduction='douban introduction',
                                                    link= data[1],
                                                    classfy='doubanhot',
                                                    onshelf=True,
                                                    keyword='豆瓣热榜',
                                                    viewnum=data[3],
                                                    content=data[4],
                                                    batchNo=int(batchNo),
                                                    )
                articleObj.save()
            endTime = time.time()
            results = dict(returnOriginJson)
            results['classfy'] = '豆瓣热榜'
            results['info'] = 'Successfully inserted douban data in {} seconds.'.format(endTime - startTime)
            return JsonResponse(results)
        except Exception as e:
            raise Exception


def getDoubanHot(request):
    if request.method == "GET":
        return JsonResponse(returnOriginJson)
    elif request.method == "POST":
        results = dict(returnOriginJson)
        try:
            classfy = str(json.loads(request.body).get('classfy'))
            # classfy = 'doubanhot'
            maxBatchNo = Article.objects.filter(classfy=classfy).aggregate(Max('batchNo'))['batchNo__max']
            articleObj = Article.objects.filter(
                Q(isdeleted=0) & Q(onshelf=1) & Q(classfy=classfy) & Q(batchNo=maxBatchNo)).values('id', 'title',
                                                                                                   'subtitle',
                                                                                                   'introduction',
                                                                                                   'content', 'link',
                                                                                                   'keyword',
                                                                                                   'classfy', 'hits',
                                                                                                   'viewnum',
                                                                                                   'ontop',
                                                                                                   'iselite', 'author',
                                                                                                   'create_time',
                                                                                                   'update_time').order_by(
                '-hits')
            results = dict(returnOriginJson)
            results['info'] = list(articleObj)
            print(results)
            return JsonResponse(results, safe=True)
        except Exception as e:
            print(e)


def addweixinHot(request):
    if request.method == "GET":
        return JsonResponse(returnOriginJson)
    elif request.method == "POST":
        results = dict(returnOriginJson)
        try:
            """
            [index, articleName, sougouSearchUrl, viewNum, readingNum]
            """
            weixinList = getWeixinData()
            print(weixinList)
            startTime = time.time()
            for index, data in enumerate(weixinList):
                batchNo = time.strftime("%Y%m%d%H%M", time.localtime(time.time()))
                articleObj = Article.objects.create(title=data[1],
                                                    introduction=data[4],
                                                    link=data[2],
                                                    classfy='weixinhot',
                                                    onshelf=True,
                                                    keyword='微信热榜',
                                                    subtitle=data[3],
                                                    batchNo=int(batchNo),
                                                    )
                articleObj.save()
            endTime = time.time()
            results = dict(returnOriginJson)
            results['classfy'] = '微信热榜'
            results['info'] = 'Successfully inserted weixin data in {} seconds.'.format(endTime - startTime)
            return JsonResponse(results)
        except Exception as e:
            raise Exception


def getWeixinData(request):
    if request.method == "GET":
        return JsonResponse(returnOriginJson)
    elif request.method == "POST":
        results = dict(returnOriginJson)
        try:
            classfy = str(json.loads(request.body).get('classfy'))
            # classfy = 'weixinhot'
            maxBatchNo = Article.objects.filter(classfy=classfy).aggregate(Max('batchNo'))['batchNo__max']
            articleObj = Article.objects.filter(
                Q(isdeleted=0) & Q(onshelf=1) & Q(classfy=classfy) & Q(batchNo=maxBatchNo)).values('id', 'title',
                                                                                                   'subtitle',
                                                                                                   'introduction',
                                                                                                   'content', 'link',
                                                                                                   'keyword',
                                                                                                   'classfy', 'hits',
                                                                                                   'viewnum',
                                                                                                   'ontop',
                                                                                                   'iselite', 'author',
                                                                                                   'create_time',
                                                                                                   'update_time').order_by(
                '-hits')
            results = dict(returnOriginJson)
            results['info'] = list(articleObj)
            print(results)
            return JsonResponse(results, safe=True)
        except Exception as e:
            print(e)

def getSentanceEveryday(request):
    if request.method == "GET":
        return JsonResponse(returnOriginJson)
    elif request.method == "POST":
        try:
            url = 'https://interface.meiriyiwen.com/article/random?dev=1'
            sentance = requests.get(url=url).json()['data']
            print(sentance)
            results = dict(returnOriginJson)
            results['info'] = sentance
            return JsonResponse(results, safe=True)
        except Exception as e:
            print(e)

